﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Xml.Linq;
using System.ServiceModel.Syndication;
using System.Xml;
using System.Configuration;
using Microsoft.Samples.ServiceHosting.StorageClient;

namespace RSSAggregator_WebRole
{
    public static class RSSReader
    {
        public static void UpdateFeed(string user,string feedName,string uri)
        {
            StorageAccountInfo accountInfo = StorageAccountInfo.GetAccountInfoFromConfiguration("TableStorageEndpoint");
            RSSAggregatorContext context = new RSSAggregatorContext(accountInfo);

            XmlReader reader = XmlReader.Create(uri);
            SyndicationFeed feed = SyndicationFeed.Load(reader);
            foreach (SyndicationItem item in feed.Items)
            {
                FeedItem feedItem = new FeedItem();
                feedItem.FeedName = feedName;
                feedItem.PartitionKey = user;
                feedItem.RowKey = (DateTime.MaxValue.Ticks - item.PublishDate.UtcDateTime.Ticks).ToString();
                feedItem.ItemName = item.Title.Text;
                feedItem.Posted = item.PublishDate.UtcDateTime;
                feedItem.ItemURL = item.Links.First().Uri.AbsoluteUri;

                context.AddObject("FeedItems2", feedItem);
                context.SaveChanges();
            }
        }
    }
}
